## Bibliotecas e Dados----------------------------------------------------------

library(tidyverse)
library(hrbrthemes)
library(patchwork)
library(janitor)
library(reshape2)
library(scales)
library(widyr)
library(ggridges)
Sys.setlocale("LC_TIME", 'portuguese')
options(scipen = 999)


### dados
load(file = "data_tables.Rdata")


# Tema
tema <-
  theme(
    plot.title = element_text(
      colour = "#2d2d2d",
      size = 28,
      face = "bold",
      family = "Roboto Condensed"
    ),
    plot.caption =  element_text(
      colour = "grey20",
      size = 10,
      face = "plain",
      family = "Roboto Condensed"
    ),
    plot.subtitle = element_text(
      colour = "grey20",
      size = 20,
      face = "plain",
      family = "Roboto Condensed"
    ),
    axis.text.y = element_text(colour = "grey20", size = 24),
    axis.title.x = element_text(colour = "grey20", size = 20),
    axis.title.y = element_text(colour = "grey20", size = 20),
    axis.text.x = element_text(colour = "grey20", size = 24),
    strip.text = element_text(
      size = 12,
      face = "bold",
      family = "Roboto Condensed"
    )
  ) +
  theme(panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank())

# Função para adicionar unidades em rótulo de gráfico
addUnits <- function(n) {
  labels <- ifelse(n < 1000, n,  # less than thousands
                   ifelse(n < 1e6, paste0(round(n / 1e3), 'k'),  # in thousands
                          ifelse(
                            n < 1e9, paste0(round(n / 1e6), 'M'),  # in millions
                            ifelse(
                              n < 1e12,
                              paste0(round(n / 1e9), 'B'),
                              # in billions
                              ifelse(n < 1e15, paste0(round(n /
                                                              1e12), 'T'), # in trillions
                                     'too big!')
                            )
                          )))
  return(labels)
}


# Cores escala ideológica
group.colors <- c(
  "medio" = "#c4c4c4",
  "pred_dir" = "#4da1bf",
  "pred_esq" = "#c75459",
  "esc_dir" = "#164f78",
  "esc_esq" = "#78161b"
)


# Fig1 --------------------------------------------------------------------

proportions %>%  group_by(faixa) %>%  summarise(total = sum(n)) %>%
  dplyr::mutate(post_percent = total / sum(total)) %>%
  na.omit() %>%
  ggplot(aes(
    x = "",
    y = post_percent,
    fill = factor(
      faixa,
      levels = c("esc_dir",
                 "pred_dir",
                 "medio",
                 "pred_esq",
                 "esc_esq")
    ),
    label = percent(post_percent)
  )) +
  geom_col(aes(width = .8), color = "white") +
  coord_flip()  +
  labs(x = "", y = "Porcentagem de publicações") +
  scale_fill_manual(
    values = group.colors,
    "Proporção",
    labels = c(
      "Exclusivamente Direita",
      "Predominantemente Direita",
      "Intermediário",
      "Predominantemente Esquerda",
      "Exclusivamente Esquerda"
    )
  )  +
  tema  +
  scale_y_percent() +
  ggrepel::geom_text_repel(
    size = 10,
    segment.size = 0.2,
    direction = "y",
    position = position_stack(vjust = .45),
    color = "white",
    check_overlap = T,
    fontface = 2
  ) +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 24,
    axis_title_just = "center",
    axis_title_size =   20
  ) +
  theme(
    legend.title = element_text(size = 18),
    legend.position = "bottom",
    legend.text = element_text(size = 18)
  ) +
  #  geom_hline(yintercept=0.5,color = "black", linetype="dotted") +
  guides(fill = guide_legend(reverse = T), guide_colorbar(reverse = T)) + theme(# Change legend key size and key width
    legend.key.size = unit(1.5, "cm"),
    legend.key.width = unit(1.5, "cm"))



# Fig2 --------------------------------------------------------------------


# histograma
p1 <- ggplot(proportions, aes(x = mpas)) +
  geom_histogram(color = "white",
                 fill = "grey30",
                 bins = 10,
                 aes(y = stat(width * density))) +
  scale_y_continuous(labels = percent_format()) +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 16,
    axis_title_just = "center",
    axis_title_size =   20
  ) +
  labs(x = "\nMedia Partisanship Attention Score", y = "Domínios\n") +
  tema

# n posts q10
p2 <- proportions %>%
  group_by(quartile_10) %>%
  summarise(n_posts = sum(n)) %>%
  ggplot(aes(quartile_10, n_posts)) +
  geom_col() +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 16,
    axis_title_just = "center",
    axis_title_size =   20
  ) +
  labs(x = "\nMPAS quartis", y = "Posts\n") +
  tema +
  expand_limits(x = c(0, NA), y = c(0, NA)) +
  scale_y_continuous(labels = addUnits) +
  scale_x_continuous(breaks = 1:10)



# n shares q10
p3 <- proportions %>%
  group_by(quartile_10) %>%
  summarise(sum_shares = sum(shares_sum)) %>%
  ggplot(aes(quartile_10, sum_shares)) +
  geom_col() +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 16,
    axis_title_just = "center",
    axis_title_size =   20
  ) +
  labs(x = "\nMPAS quartis", y = "Compartilhamentos\n(Total)\n") +
  tema +
  expand_limits(x = c(0, NA), y = c(0, NA)) +
  scale_y_continuous(labels = addUnits) +
  scale_x_continuous(breaks = 1:10)

# mean shares q10
p4 <- proportions %>%
  group_by(quartile_10) %>%
  summarise(mean_shares = mean(shares_sum)) %>%
  ggplot(aes(quartile_10, mean_shares)) +
  geom_col() +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 16,
    axis_title_just = "center",
    axis_title_size =   20
  ) +
  labs(x = "\nMPAS quartis", y = "Compartilhamentos\n(Média)\n") +
  tema +
  expand_limits(x = c(0, NA), y = c(0, NA)) +
  scale_y_continuous(labels = addUnits) +
  scale_x_continuous(breaks = 1:10)


# Agrupar plots
p1 + p2 + p3 + p4 + plot_annotation(tag_levels = 'A')

# Exportar Figura
ggsave("fig2.jpeg",
       width = 12,
       height = 8,
       dpi = 300)

# Exportar Dados
write.csv(proportions, "fig1_2_3_data.csv")



# Fig3 --------------------------------------------------------------------
# Gerar gráfico de densidade por categoria
ggplot(proportions, aes(x = mpas, y = tipo), color = NULL) +
  stat_density_ridges(
    quantile_lines = TRUE,
    quantiles = 2,
    size = 1.2,
    scale = .9,
    color = "white"
  ) + tema +
  hrbrthemes::theme_ipsum_rc(
    grid = "X",
    axis_text_size = 20,
    axis_title_just = "center",
    axis_title_size =   26
  ) + labs(x = "MPAS", y = "")


# Exportar figura
ggsave("fig3.jpeg", width = 12, height = 8, dpi = 300)




# Fig4 --------------------------------------------------------------------
# Gerar gráfico
year_shares %>%
  ggplot(aes(x = ano, y = sum_shares)) +
  geom_line(
    data = year_shares %>% dplyr::select(-label),
    aes(group = domain),
    color = "grey",
    size = 2,
    alpha = 0.3
  ) +
  geom_line(aes(color = domain, group = domain),
            color = "skyblue",
            size = 3.2) +
  geom_point(
    color = "skyblue",
    fill = "white",
    size = 4.5,
    shape = 21
  ) + # keep expand
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_title_family = "Roboto Condensed",
    axis_title_face = "bold",
    axis_text_size = 16,
    caption_size = 16,
    axis_title_just = "center",
    axis_title_size =   20,
    plot_title_size = 38,
    subtitle_size = 32
  )  +
  labs(x = "", y = "Compartilhamentos\n") +
  facet_wrap( ~ label, nrow = 3) +
  scale_x_date(date_breaks   = "1 year",
               labels = date_format("%Y")) +
  expand_limits(x = as.Date(c("2011-01-01", "2020-01-01"))) +
  theme(strip.text.x = element_text(size = 16, face = "bold", color = "grey30")) +
  scale_y_continuous(labels = addUnits) +
  ggrepel::geom_text_repel(
    data = filter(year_shares, ano == as.Date("2019-01-01")),
    aes(label = domain),
    color = "black",
    size = 5,
    direction = "y" ,
    alpha = .9,
    hjust = -.5,
    fontface = "italic",
    family = "Roboto Condensed"
  ) +
  theme(
    legend.text = element_text(colour = "grey20", size = 20),
    legend.title = element_text(colour = "grey20", size = 20),
    strip.text.x = element_text(
      colour = "grey20",
      size = 18,
      face = "bold"
    )
  )

# Gerar gráfico
ggsave("fig4.jpg", width = 13, height = 10, dpi = 300)

# Exportar Dados
write.csv(year_shares, "fig4_data.csv")


# Fig5 --------------------------------------------------------------------
# Calcular erro padrão
sem <- sd(res_normalized$value) / sqrt(length(res_normalized$value))

# Gerar gráfico
res_normalized %>%
  ggplot(aes(
    x = ano,
    y = value,
    group = variable,
    fill = variable
  )) +
  geom_line(aes(color = variable), size = 3) +
  geom_ribbon(aes(ymin = value - 2 * sem, ymax = value + 2 * sem),
              alpha = 0.2) +
  geom_point(aes(color = variable),
             size = 4,
             shape = 21,
             fill = "white") +
  labs(
    x = "",
    y = "Porcentagem de menções",
    domain = "Dados extraídos pela Facebook Graph API
       Área sombreada indica margem de erro com 95% de confiança"
  ) +
  guides(color = guide_legend(title = "Posicionamento de Rede")) +
  tema + scale_y_continuous(labels = percent_format(), limits = c(0, 1)) +
  scale_color_manual(
    name = "Rede",
    values = c("indianred", "skyblue"),
    labels = c("Esquerda", "Direita")
  ) +
  ggrepel::geom_text_repel(aes(label = percent(value, accuracy = .1)),
                           #fontface = 'bold',
                           size = 6) + scale_fill_discrete(guide = FALSE) +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 20,
    caption_size = 16,
    axis_title_just = "center",
    axis_title_size =   22
  ) +
  theme(legend.position = "bottom") +
  theme(
    legend.text = element_text(colour = "black", size = 20),
    legend.title = element_text(colour = "black", size = 20)
  )

# Exportar figura
ggsave("fig5.jpeg", width = 12, height = 8, dpi = 300)

# Exportar Dados
write.csv(res_normalized, "fig5_data.csv")



# Fig6 --------------------------------------------------------------------
# Calcular erro padrão
sem <- sd(res_normalized_dom$value) / sqrt(length(res_normalized_dom$value))

# Gerar gráfico
p <- res_normalized_dom %>%
  ggplot(aes(
    x = ano,
    y = value,
    group = variable,
    fill = variable
  )) +
  geom_line(aes(color = variable), size = 1.8) +
  geom_ribbon(aes(ymin = value - 2 * sem, ymax = value + 2 * sem),
              alpha = 0.2) +
  geom_point(aes(color = variable),
             size = 4,
             shape = 21,
             fill = "white") +
  labs(
    x = "",
    y = "",
    domain = "Dados extraídos pela Facebook Graph API
       Área sombreada indica margem de erro com 95% de confiança"
  ) +
  guides(color = guide_legend(title =
                                                                    "Posicionamento de Rede")) +
  tema + scale_y_continuous(labels = percent_format(), limits = c(0, 1)) +
  scale_color_manual(
    name = "Rede",
    values = c("indianred", "skyblue"),
    labels = c("Esquerda", "Direita")
  ) +
  ggrepel::geom_text_repel(aes(label = percent(value, accuracy = .1)),
                           #fontface = 'bold',
                           size = 4) + scale_fill_discrete(guide = FALSE) + facet_wrap( ~ domain, ncol = 3) +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 12,
    caption_size = 12,
    axis_title_just = "center",
    axis_title_size =   12
  ) +
  theme(legend.position = "bottom")  +
  theme(
    legend.text = element_text(colour = "grey20", size = 20),
    legend.title = element_text(colour = "grey20", size = 20),
    strip.text = element_text(
      colour = "grey20",
      size = 14,
      face = "bold"
    )
  )

# Gerar gráfico
ggsave("fig6.jpeg",plot = p,width = 14, height = 8, dpi = 300)

# Exportar Dados
write.csv(res_normalized_dom, "fig6_data.csv")

# Fig7 --------------------------------------------------------------------
# Gerar gráfico
ajst %>%
  filter(tipo == "Imprensa") %>%
  ggplot(aes(
    x = ano,
    y = ajustado,
    group = esq_dir,
    fill = esq_dir
  )) +
  geom_line(aes(color = esq_dir), size = 4) +
  #geom_ribbon(aes(ymin=value-2*sem, ymax=value+2*sem),
  #            alpha=0.2)+
  geom_point(aes(color = esq_dir),
             size = 4,
             shape = 21,
             fill = "white") +
  labs(
    x = "",
    y = "Porcentagem de menções",
    domain = "Dados extraídos pela Facebook Graph API
       Área sombreada indica margem de erro com 95% de confiança"
  ) +
  theme_ipsum("X") +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.grid.minor.y = element_blank()
  ) +
  theme(legend.position = "bottom") + 
  guides(color = guide_legend(title = "Posicionamento de Rede")) +
  tema +
    scale_color_manual(name = "Rede", values = c("skyblue", "indianred")) +
  ggrepel::geom_text_repel(aes(label = percent(ajustado, accuracy = .01)),
                           #fontface = 'bold',
                           size = 6) + scale_fill_discrete(guide = FALSE) +
  scale_y_percent() + expand_limits(y = c(0, 0.1)) +
  hrbrthemes::theme_ipsum_rc(
    grid = "Y",
    axis_text_size = 16,
    caption_size = 16,
    axis_title_just = "center",
    axis_title_size =   20
  ) +
  theme(legend.position = "bottom") +
  theme(
    legend.title = element_text(size = 22),
    legend.position = "bottom",
    legend.text = element_text(size = 22)
  )


# Exportar figura
ggsave("fig7.jpeg", width = 12, height = 8, dpi = 300)

# Exportar Dados
write.csv(ajst, "fig7_data.csv")

